<template>
	<div class="qrcode-container">
		<div id="qrcodeRef" ref="qrcodeRef"></div>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, defineComponent, onMounted, onUnmounted, watch } from 'vue';
import QRCode from 'qrcodejs2-fixes';
import { ElMessage } from 'element-plus';
import { getScanAuthorize } from '/@/api/login/index';

export default defineComponent({
	name: 'login/qrcode',
	props: {
		// 绑定值
		model: {
			type: String,
			default: () => 'QQ',
		},
	},
	setup(props) {
		const qrcodeRef = ref<HTMLElement | null>(null);
		const state = reactive({
			handleMessage: undefined,
		});
		
		// 显示二维码
		const onShowQRCode = (mode: string) => {
			switch(mode){
				case 'QQ':
					qqQRCode();
					break;
				case 'WEIXIN':
					weixinQRCode();
					break;
				case 'QIYE_WEIXIN':
					qiyeweixinQRCode();
					break;
				case 'FEISHU':
					feishuQRCode();
					break;
				case 'DINGDING':
					dingdingQRCode();
					break;
				default:
					break;
			}
		}
		
		const qqQRCode = () => {
			(qrcodeRef.value as HTMLElement).innerHTML = '';
			//TODO
			getScanAuthorize({mode: 'QQ'}).then((res: any) => {
				if(res.code === 0){
					const authorizeUri = res.data.authorizeUri;
					new QRCode(qrcodeRef.value, {
						text: authorizeUri,
						width: 234,
						height: 234,
						colorDark: '#000000',
						colorLight: '#ffffff',
					});
				}
			})
		}
		
		const weixinQRCode = () => {
			(qrcodeRef.value as HTMLElement).innerHTML = '';
			//TODO
			getScanAuthorize({mode: 'WEIXIN'}).then((res: any) => {
				if(res.code === 0){
					const {redirectUri, clientId, state} = res.data;
					new WxLogin({
						self_redirect: false,
						id: (qrcodeRef.value as HTMLElement).id, 
						appid:  clientId,
						scope: 'snsapi_login',
						redirect_uri: redirectUri,
						state: state,
						style: 'white',
						href: ''
					});
				}
			})
		}
		
		const qiyeweixinQRCode = () => {
			(qrcodeRef.value as HTMLElement).innerHTML = '';
			//TODO
			getScanAuthorize({mode: 'QIYE_WEIXIN'}).then((res: any) => {
				if(res.code === 0){
					const {redirectUri, clientId, agentId, state} = res.data;
					new WwLogin({
						self_redirect: false,
						id: (qrcodeRef.value as HTMLElement).id,  
						appid: clientId,
						agentid: agentId,
						redirect_uri: redirectUri,
						state: state,
						href: '',
						lang: 'zh',
					});
				}
			})
		}
		
		const feishuQRCode = () => {
			(qrcodeRef.value as HTMLElement).innerHTML = '';
			//TODO
			getScanAuthorize({mode: 'FEISHU'}).then((res: any) => {
				if(res.code === 0){
					const authorizeUri = res.data.authorizeUri;
					const QRLoginObj = QRLogin({
						id: (qrcodeRef.value as HTMLElement).id,
						width: '234',
						height: '234',
						goto: authorizeUri,
						style: 'width:260px;height:260px;border:0;'
					});
					
					const handleMessage = (event: any) => {
						const origin = event.origin;    
						// 使用 matchOrigin 方法来判断 message 来自页面的url是否合法
						if( QRLoginObj.matchOrigin(origin) ) {
							const tmp_code = event.data;
							// 在授权页面地址上拼接上参数 tmp_code，并跳转
							window.location.href = `${authorizeUri}&tmp_code=${tmp_code}`;
						}
					};
					state.handleMessage = handleMessage as any;
					if (typeof window.addEventListener != 'undefined') {   
						window.addEventListener('message', state.handleMessage, false);} 
					else if (typeof window.attachEvent != 'undefined') {
						window.attachEvent('onmessage', state.handleMessage);
					}
				}
			})
		}
		
		const dingdingQRCode = () => {
			(qrcodeRef.value as HTMLElement).innerHTML = '';
			//TODO
			getScanAuthorize({mode: 'DINGDING'}).then((res: any) => {
				if(res.code === 0){
					const {redirectUri, clientId, state} = res.data;
					window.DTFrameLogin({
						id: (qrcodeRef.value as HTMLElement).id,
						width: 240,
						height: 240,
					},{
						redirect_uri: encodeURIComponent(redirectUri),
						client_id: clientId,
						scope: 'openid',
						response_type: 'code',
						state: state,
						prompt: 'consent',
					},
					(loginResult: any) => {
						const {authCode, state} = loginResult;
						// 这里可以直接进行重定向
						window.location.href = `${redirectUri}?code=${authCode}&state=${state}`;
					},
					(errorMsg: any) => {
						// 这里一般需要展示登录失败的具体原因
						ElMessage.error(errorMsg);
					});
				}
			})
		}
		
		// 页面加载时
		onMounted(() => {
			onShowQRCode(props.model);
		});
		
		onUnmounted(() => {
			window.removeEventListener('message', state.handleMessage, false);
		});
		
		watch(() => props.model, (model) => {
			onShowQRCode(model);
		})
		
		return { 
			qrcodeRef,
			...toRefs(state),
		};
	},
});
</script>
